package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.db.domain.*;
import com.mall.db.service.*;
import com.mall.db.service.MemberService;
import com.mall.db.service.MembersService;
import com.mall.db.service.OrderService;
import com.mall.db.service.SchedulerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 页面跳转控制器
 */
@Controller
@RequestMapping("/page")
public class PageController {

    @Value("${email.times}")
    private long emailTimes;


    @Resource(name = "memberService")
    private MemberService ms;
    @Resource(name = "brandService")
    private BrandService bs;
    @Resource(name = "membersService")
    private MembersService mss;

    @Resource(name = "schedulerService")
    private SchedulerService ss;
    @Resource(name = "commentService")
    private CommentService cts;

    @Resource(name = "couponService")
    private CouponService cs;

    @Resource(name = "itemCatService")
    private ItemCatService is;

    @Resource(name = "orderService")
    private OrderService os;

    @Resource(name = "commodityService")
    private  CommodityService cms;
    @Resource(name = "stockService")
    private  StockService sss;


    @RequestMapping("/index")
    public String index(){
        return "/views/index";
    }
    @RequestMapping("/login")
    public String login(){
        return "/views/login";
    }
    @RequestMapping("/forgetPwd")
    public String forgetPwd(){
        return "/views/forgetPwd";
    }

    @RequestMapping("/forgetNext")
    public String forgetNext(@RequestParam(name = "email")String email,
                             ModelMap mmap){
        mmap.addAttribute("email",email);
        return "/views/forgetNext";
    }
    @RequestMapping("/forgetVerify")
    public String forgetVerify(@RequestParam(name = "code")String code,
                               @RequestParam(name = "token")String token,
                               ModelMap mmap, HttpServletResponse res, HttpSession session){
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            code = new String(decoder.decodeBuffer(code), "utf-8");
            token = new String(decoder.decodeBuffer(token), "utf-8");
            //判断时间的有效性
             if(System.currentTimeMillis()-Long.parseLong(code)> emailTimes){
               mmap.addAttribute("tips","邮件链接已过期，请重新获取！");
                return "/views/tips";
             }
             if(!StringUtils.isEmpty(token)){
                 QueryWrapper<Member> qw=new QueryWrapper<>();
                 qw.eq("email",token);
                 Member m=ms.getOne(qw);
                 if(m!=null){
                     mmap.addAttribute("id",m.getId());
                     mmap.addAttribute("email",token);
                     code=new Random().nextInt(999)+10000+"";
                     session.setAttribute("mobileCode",code);
                     mmap.addAttribute("code",code);
                     return "/views/pwdEdit";
                 }else {
                     mmap.addAttribute("tips","该邮箱未注册到系统!");
                     return "/views/tips";
                 }
             }
        }catch (Exception e){
            e.printStackTrace();
        }
        mmap.addAttribute("tips","密码找回失败！");
        return "/views/tips";
    }

    @RequestMapping("/main")
    public String main(){
        return "/views/main";
    }
    @RequestMapping("/members")
    public String members(){
        return "/views/system/members";
    }
    @RequestMapping("/address")
    public String address(){
        return "/views/system/address";
    }
    @RequestMapping("/region")
    public String region(){
        return "/views/system/region";
    }

    @RequestMapping("/{root}/{pageName}")
    public String createPageLink(@PathVariable(name = "root") String root,
                                 @PathVariable(name = "pageName") String pageName){
        return String.format("/views/%s/%s",root,pageName);
    }
    @RequestMapping("/system/memberEdit/{id}")
    public String pageUpdate(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("m",ms.getById(id));
        return String.format("/views/system/memberEdit");
    }

    @RequestMapping("/system/membersEdit/{id}")
    public String membersEdit(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("m",mss.getById(id));
        return String.format("/views/system/membersEdit");
    }
    @RequestMapping("/system/setUp/{id}")
    public String setUp(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("s",sss.getById(id));
        return String.format("/views/system/setUp");
    }

    @RequestMapping("/system/brandEdit/{id}")
    public String pageUpdate1(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("b",bs.getById(id));
        return String.format("/views/system/brandEdit");
    }
    @RequestMapping("/system/commentLook/{id}")
    public String commentLook(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("c",cts.getById(id));
        return String.format("/views/system/commentLook");
    }
    @RequestMapping("/system/commentReply/{id}")
    public String commentReply(@PathVariable(name = "id") int id,
                             ModelMap mmap){
        mmap.addAttribute("c",cts.getById(id));
        return String.format("/views/system/commentReply");
    }

    @RequestMapping("/system/editQuartz/{jobName}")
    public String editQuartz(@PathVariable (value = "jobName")String jobName,ModelMap mmap){
        mmap.addAttribute("s",ss.getByJobName(jobName));
        return "/views/system/editQuartz";
    }
    @RequestMapping("/system/map/{lng}/{lat}")
    public String map(@PathVariable(name = "lng") double lng,
                      @PathVariable(name = "lat") double lat,
                             ModelMap mmap){
        //TODO 获取该用户登录时，所在的城市信息，经纬度
        lng=lng==0.0?108.281113:lng;
        lat=lat==0.0?22.868199:lat;
        mmap.addAttribute("lng",lng);
        mmap.addAttribute("lat",lat);
        return "/views/system/map";
    }
    //修改优惠券页面
    @RequestMapping("/system/couponEdit/{id}")
    public String couponEdit(@PathVariable(name = "id")int id,ModelMap mmap){
        Coupon coupon = cs.getById(id);
        if (coupon.getTimeType()==1&&coupon.getStartTime()!=null&&coupon.getEndTime()!=null){
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = coupon.getStartTime();
            Date endTime = coupon.getEndTime();
            String sTime =  s.format(startTime);
            String eTime =  s.format(endTime);
            mmap.addAttribute("sTime",sTime);
            mmap.addAttribute("eTime",eTime);
        }
        mmap.addAttribute("c",coupon);
        return "/views/system/couponEdit";
    }
    @RequestMapping("/system/couponDetails/{id}")
    public String couponDetails(@PathVariable(name = "id")int id,ModelMap mmap){
        Coupon coupon  = cs.getById(id);
        mmap.addAttribute("c",coupon);
        return "/views/system/couponDetails";
    }
    @RequestMapping("/details/{id}")
    public String details(@PathVariable (name = "id")int id,
                          ModelMap mmap){
        Order order =os.getById(id);
        mmap.addAttribute("order",order);
        return "/views/system/details";
    }
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable(name = "id")int id,
                          ModelMap mmap){
        Commodity commodity =cms.getById(id);
        mmap.addAttribute("c",commodity);
        return "/views/system/commoditydetails";
    }
    @RequestMapping("/itemCatEdit/{id}")
    public String itemCatEdit (@PathVariable(name = "id") int id,

                               ModelMap mmap){
        ItemCat itemCat = is.getById(id);
        mmap.addAttribute("i",itemCat);
       /* int iid = itemCat.getPid();
        ItemCat i = is.getById(iid);
        mmap.addAttribute("p",i);*/
        return String.format("/views/system/itemCatEdit");
    }
}
